package com.hooya.fa.eu.biz.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.hooya.fa.eu.api.bo.JpkStockBO;
import com.hooya.fa.eu.api.bo.WmsKcInfoBO;
import com.hooya.fa.eu.api.bo.report.PkpyBO;
import com.hooya.fa.eu.api.bo.report.ProfitCheckBO;
import com.hooya.fa.eu.api.bo.report.jpk.JpkInfoBO;
import com.hooya.fa.eu.api.bo.report.jpk.JpkRecordInfoBO;
import com.hooya.fa.eu.api.bo.stk.BuyRecordBO;
import com.hooya.fa.eu.api.enums.CkEnum;
import com.hooya.fa.eu.api.util.DateExtUtil;
import com.hooya.fa.eu.api.util.FileUtil;
import com.hooya.fa.eu.biz.dao.entity.*;
import com.hooya.fa.eu.biz.dao.entity.rxh.DeliverGoods;
import com.hooya.fa.eu.biz.dao.entity.rxh.DeliverGoodsSheet;
import com.hooya.fa.eu.biz.dao.manager.GeneratorEntityManager;
import com.hooya.fa.eu.biz.dao.mapper.*;
import com.hooya.fa.eu.biz.dao.mapper.rxh.DeliverGoodsMapper;
import com.hooya.fa.eu.biz.dao.mapper.rxh.DeliverGoodsSheetMapper;
import com.hooya.fa.eu.biz.dao.mapper.stk.TempPkpyMapper;
import com.hooya.fa.eu.biz.dao.mapper.stk.TempZyjlDeleteMapper;
import com.hooya.fa.eu.biz.dao.mapper.stk.TempZyjlMapper;
import com.hooya.fa.eu.biz.dao.wrapper.DeliverGoodsSheetWrapper;
import com.hooya.fa.eu.biz.dao.wrapper.DeliverGoodsWrapper;
import com.hooya.fa.eu.biz.service.DictRelationService;
import com.hooya.fa.eu.biz.service.EuSourceDataService;
import com.hooya.fa.eu.biz.service.TempRelationService;
import com.hooya.fa.eu.biz.service.TempService;
import com.hooya.integrated.common.core.util.BeanCopyUtils;
import com.hooya.integrated.common.core.util.DoubleUtil;
import com.hooya.integrated.common.core.util.RedisUtils;
import com.hooya.integrated.common.other.data.DataMethod;
import com.hooya.integrated.common.util.currency.CurrencyConvertUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.hooya.fa.eu.api.constant.FileNameConstant.JPK_FOLDER_NAME;
import static com.hooya.fa.eu.api.constant.FileNameConstant.WMS_FOLDER_NAME;

/**
 * @Description 1
 * @Author : Zongz
 * @Copyright Copyright (c) 豪雅集团
 * @Create 2024/1/31
 * @Version 1.0.0
 */
@Slf4j
@Service
@DS("europe")
@AllArgsConstructor
public class TempServiceImpl implements TempService {

    private final GeneratorEntityManager generatorEntityManager;

    private final TempMapper tempMapper;

    private final DeliverGoodsMapper deliverGoodsMapper;

    private final DeliverGoodsSheetMapper deliverGoodsSheetMapper;

    private final CkDictMapper dictMapper;

    private final EuSourceDataService euSourceDataService;
    private final DictRelationService dictRelationService;
    private final TempRelationService tempRelationService;

    private final TempKcjlDailyMapper tempKcjlDailyMapper;
    private final TempPkpyMapper temPkpyMapper;
    private final TempZyjlMapper tempZyjlMapper;
    private final TempZyjlDeleteMapper tempZyjlDeleteMapper;

    private final WmsKcMapper wmsKcMapper;

    private final PkMapper pkMapper;

    public static boolean b;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDistinctData() {
        b = false;
        do {
            b = checkRepeatData();
        } while (!b);
    }

    public boolean checkRepeatData() {
        List<String> checkIds = tempMapper.getRepeatId();
        if (CollectionUtils.isEmpty(checkIds)) {
            return true;
        }
        List<DeliverGoods> List = deliverGoodsMapper
                .selectList(DeliverGoodsWrapper.newQuery().inIds(checkIds));
        Map<String, List<DeliverGoods>> deliverGoodsMap = List.stream()
                .collect(Collectors.groupingBy(DeliverGoods::getId));
        deliverGoodsMap.forEach((id, list) -> {
            List<DeliverGoods> deleted = list.stream()
                    .filter(l -> l.getIsDelete() == 1).collect(Collectors.toList());
            //只要是delete，随便删哪一条
            if (deleted.size() > 0) {
                System.out.println(tempMapper.deleteDistinctDataByDelete(deleted.get(0).getId()) + ",id:" + deleted.get(0).getId());
                return;
            }
            List<DeliverGoods> print = list.stream()
                    .filter(l -> l.getIsPrint() == 0).collect(Collectors.toList());
            if (print.size() > 0) {
                System.out.println(tempMapper.deleteDistinctDataByPrint(print.get(0).getId()) + ",id:" + print.get(0).getId());
                return;
            }
            //不是以上2种情况，且数据都相等
            System.out.println(tempMapper.deleteDistinctData(list.get(0).getId()) + ",id:" + list.get(0).getId());
        });
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDistinctSheetData() {
        b = false;
        do {
            b = checkSheetRepeatData();
        } while (!b);
    }

    public boolean checkSheetRepeatData() {
        List<String> checkIds = tempMapper.getSheetRepeatId();
        if (CollectionUtils.isEmpty(checkIds)) {
            return true;
        }
        List<DeliverGoodsSheet> List = deliverGoodsSheetMapper
                .selectList(DeliverGoodsSheetWrapper.newQuery().inIds(checkIds));
        Map<String, List<DeliverGoodsSheet>> sheetMap = List.stream()
                .collect(Collectors.groupingBy(DeliverGoodsSheet::getId));
        sheetMap.forEach((id, list) -> {
            DeliverGoodsSheet sheet = list.stream()
                    .min(Comparator.comparingInt(DeliverGoodsSheet::getStatus)).get();
            System.out.println(tempMapper.deleteDistinctSheetData(sheet.getId(), sheet.getStatus()) +
                    ",id:" + list.get(0).getId());
        });
        return false;
    }

    @Override
    @DS("fa_eu")
    public void getDict(String name) {
//        Map<String, List<String>>
        Map<String, Object> map = getMap();
        RedisUtils.hmset("dict_cache::" + CkEnum.FBA_CK_MAP.getName(), map);
    }

    public Map<String, Object> getMap() {
        List<CkDict> dictList = dictMapper.getCostWayFbaCkList(CkEnum.FBA_CK_MAP.getName(), "COSTWAY");
        Map<String, Object> result = dictList.stream()
                .filter(a -> a.getParentId() == -1) // Only include parent (top-level) items
                .collect(Collectors.toMap(
                        CkDict::getParamKey, // The outer map key is the 'key' from the parent item
                        parent -> dictList.stream()
                                .filter(child -> child.getParentId() == parent.getId()) // Filter children of the current parent
                                .collect(Collectors.groupingBy(
                                        CkDict::getParamKey, // Inner map key is the 'key' from the child items
                                        LinkedHashMap::new, // Use a LinkedHashMap to preserve insertion order
                                        Collectors.mapping(
                                                CkDict::getParamValue, // Collect the 'value' field
                                                Collectors.toList() // Collect values into a List
                                        )
                                ))
                ));
        System.out.println(result);
        return result;
    }

    @Override
    public void getCacheDict() {
        Map<Object, Map<String, List<String>>> map = RedisUtils.hmget(CkEnum.FBA_CK_MAP.getName());
        System.out.println(map);
    }

    @Override
    @DSTransactional
    public void warehouseMigration(String startDate, String endDate) {
        //新增/更新(除07以外的) 库存数据集合
        List<TempKcjlDaily> kcjlList = new LinkedList<>();
        //转运集合
        List<TempZyjl> tempZyjlList = new LinkedList<>();
        //盘亏盘盈集合
        List<TempPkpy> pkpyList = new LinkedList<>();
        //转运删除集合
        List<TempZyjlDelete> tempZyjlDeleteList = new ArrayList<>();

        //仓库国家
        Map<String, String> metaWarehouseMap = dictRelationService.getMetaWarehouseMap();
        //转运数据
        List<PlaceMatchDict> placeMatchDictList = dictRelationService.getPlaceMatchList();
        Map<String, PlaceMatchDict> placeMatchDictMap = placeMatchDictList.stream()
                .collect(Collectors.toMap(PlaceMatchDict::getVirtualWhId, i -> i));
        List<BuyRecordBO> zyList = euSourceDataService.getZyListByDate(startDate, endDate).stream()
                .filter(l -> l.getZcck().equals("EU07")).collect(Collectors.toList());
        //仓库数据（库存）
        String yesterday = DateExtUtil.getYesterday(startDate);
        List<TempKcjlDaily> inventoryList = tempRelationService.getKcjlListByDate(yesterday);
        //zcckList最后做盘亏盘盈
        List<TempKcjlDaily> zcckList = inventoryList.stream()
                .filter(l -> l.getPlace().equals("EU07")).collect(Collectors.toList());

        Date createTime = new Date();
        //处理EU07转运
        for (BuyRecordBO zy : zyList) {
            if (zcckList.stream().noneMatch(l -> l.getCpbh().equals(zy.getCpbh()))) {
                tempZyjlDeleteList.add(BeanCopyUtils.copyPropertiesNew(zy, TempZyjlDelete::new,
                        (s, t) -> t.setCreateTime(createTime)));
                continue;
            }
            if (zy.getZlck().equals("EU生资库")) {
                continue;
            }
            List<TempKcjlDaily> kcList = zcckList.stream()
                    .filter(l -> l.getCpbh().equals(zy.getCpbh())).collect(Collectors.toList());
            for (int i = 0; i < kcList.size(); i++) {
                TempKcjlDaily kc = kcList.get(i);
                int num = kc.getSl() - zy.getCgsl();
                //当前货权的该sku减扣完了
                if (Math.max(num, 0) == 0) {
                    //新增库存转入、转运
                    addData(startDate, kc.getSl(), createTime, zy, kc, metaWarehouseMap, inventoryList, tempZyjlList, kcjlList);
                    zcckList.stream().filter(l -> l.getCpbh().equals(zy.getCpbh())).forEach(l -> {
                        l.setSl(0);
                        l.setCreateTime(createTime);
                    });
                    //最后一个
                    if (i + 1 == kcList.size()) {
                        //还有没扣完
                        if (num != 0) {
                            TempPkpy pkpy = TempPkpy.builder().cpbh(zy.getCpbh()).place(zy.getZcck())
                                    .sl(num).belongs(kc.getBelongs()).date(zy.getHtrq()).createTime(createTime).build();
                            pkpyList.add(pkpy);
                        }
                        break;
                    }
                    zy.setCgsl(Math.abs(num));
                } else {
                    addData(startDate, zy.getCgsl(), createTime, zy, kc, metaWarehouseMap, inventoryList, tempZyjlList, kcjlList);
                    zcckList.stream().filter(l -> l.getCpbh().equals(zy.getCpbh())).forEach(l -> {
                        l.setSl(num);
                        l.setCreateTime(createTime);
                    });
                    kc.setSl(num);
                    break;
                }
            }
        }
        //pkpy
        List<TempKcjlDaily> list = zcckList.stream().filter(l -> l.getSl() != 0).collect(Collectors.toList());
        list.forEach(l -> {
            int sl = l.getSl();
            pkpyList.add(BeanCopyUtils.copyPropertiesNew(l, TempPkpy::new, (s, t) -> {
                t.setId(null);
                t.setDate(startDate);
                t.setCreateTime(createTime);
                t.setSl(-sl);
                l.setSl(0);
            }));
        });
        List<TempKcjlDaily> szkList = kcjlList.stream().filter(l -> l.getPlace().equals("EU生资库")).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(szkList)) {
            szkList.forEach(l -> pkpyList.add(TempPkpy.builder().belongs(l.getBelongs()).cpbh(l.getCpbh())
                    .place("EU07").sl(l.getSl()).date(startDate).createTime(createTime).build()));
        }
        //更新非EU07数据准备
        List<TempKcjlDaily> updateKcList = kcjlList.stream()
                .filter(l -> Objects.nonNull(l.getId()) && !l.getPlace().equals("EU生资库")).collect(Collectors.toList());
        //新增非EU07数据准备
        kcjlList.removeAll(updateKcList);
        kcjlList = kcjlList.stream().filter(l -> !l.getPlace().equals("EU生资库")).collect(Collectors.toList());
        //do insert/update
        if (!CollectionUtils.isEmpty(updateKcList)) {
            for (TempKcjlDaily kcjlDaily : updateKcList) {
                tempKcjlDailyMapper.updateById(kcjlDaily);
            }
        }
        if (!CollectionUtils.isEmpty(kcjlList)) {
            tempKcjlDailyMapper.insertBatchSomeColumn(kcjlList);
        }
        if (!CollectionUtils.isEmpty(tempZyjlList)) {
            tempZyjlMapper.insertBatchSomeColumn(tempZyjlList);
        }
        if (!CollectionUtils.isEmpty(pkpyList)) {
            temPkpyMapper.insertBatchSomeColumn(pkpyList);
        }
        if (!CollectionUtils.isEmpty(tempZyjlDeleteList)) {
            tempZyjlDeleteMapper.insertBatchSomeColumn(tempZyjlDeleteList);
        }
    }

    private void addData(String day, int num, Date createTime, BuyRecordBO zy, TempKcjlDaily kc,
                         Map<String, String> metaWarehouseMap, List<TempKcjlDaily> inventoryList,
                         List<TempZyjl> tempZyjlList, List<TempKcjlDaily> kcjlList) {
        String zlOrigin = metaWarehouseMap.get(zy.getZlck());
        //如果库存有，转到与转出相同货权。如果库存没有，现在处理是删除了该转运（还有一种做法：盘赢做一条，直接新增一条fds-{zlOrigin}的数据）
        String zlBelongs = kc.getBelongs().split("-")[0] + "-" + zlOrigin;
        if (inventoryList.stream().anyMatch(l -> l.getCpbh().equals(zy.getCpbh()) &&
                l.getPlace().equals(zy.getZlck()) && l.getBelongs().equals(zlBelongs))) {
            TempKcjlDaily daily = inventoryList.stream().filter(l ->
                    l.getCpbh().equals(zy.getCpbh()) &&
                            l.getPlace().equals(zy.getZlck()) &&
                            l.getBelongs().equals(zlBelongs)).findFirst().get();
            kcjlList.add(BeanCopyUtils.copyPropertiesNew(daily, TempKcjlDaily::new, (s, t) -> {
                t.setSl(s.getSl() + num);
                t.setCreateTime(createTime);
            }));
        } else {
            TempKcjlDaily kcjlDaily = TempKcjlDaily.builder().belongs(zlBelongs).place(zy.getZlck())
                    .cpbh(zy.getCpbh()).date(day).createTime(createTime).sl(num).build();
            kcjlList.add(kcjlDaily);
        }
        if (!zy.getZlck().equals("EU生资库")) {
            TempZyjl zyjl = TempZyjl.builder().cpbh(zy.getCpbh()).zcck(zy.getZcck()).zlck(zy.getZlck())
                    .cgsl(num).hthm(zy.getHthm()).htrq(zy.getHtrq()).frombelongs(kc.getBelongs())
                    .tobelongs(zlBelongs).fromcountry(kc.getBelongs().split("-")[1]).tocountry(zlOrigin)
                    .sheetnumber(zy.getSheetNumber()).createTime(createTime).build();
            tempZyjlList.add(zyjl);
        }
    }

    @Override
    public void warehouseMigrationRectify() {
        String path = FileUtil.getExcelPath() + "warehouseMigrationRectify.xlsx";
        List<PkpyBO> list = EasyExcel.read(path).head(PkpyBO.class).sheet().doReadSync();
        Date date = new Date();
        List<TempPkpy> pkpyList = BeanCopyUtils.copyListProperties(
                list.stream().filter(l -> l.getSl() != 0).collect(Collectors.toList()),
                TempPkpy::new, (s, t) -> {
                    t.setDate("2024-05-01");
                    t.setCreateTime(date);
                });
        temPkpyMapper.insertBatchSomeColumn(pkpyList);
    }

    @Override
    @DS("fa_eu")
    @Transactional
    public void positionSupplement() {
        List<WmsKc> res = new ArrayList<>();
        String path = FileUtil.getExcelPath() + WMS_FOLDER_NAME;
        List<String> fileNameList = FileUtil.getFileNamesByPath(path);
        for (String fileName : fileNameList) {
            String country = fileName.substring(5, 7);
            List<WmsKcInfoBO> list = EasyExcel.read(path + fileName).head(WmsKcInfoBO.class)
                    .sheet("详细信息").doReadSync();
            res.addAll(BeanCopyUtils.copyListProperties(list, WmsKc::new, (s, t) -> {
                t.setCountry(country);
                t.setDate("2024-12-31");
            }));
        }
        List<List<WmsKc>> splitData = DataMethod.splitData(res, 4000);
        for (List<WmsKc> data : splitData) {
            wmsKcMapper.insertBatchSomeColumn(data);
        }
    }

    @Override
    @DS("fa_eu")
    @DSTransactional
    public void evenUp(String date) {
        List<TempKcjlDaily> addKcList = new LinkedList<>();
        List<TempKcjlDaily> updateKcList = new LinkedList<>();
        List<String> excludeSkuList = Arrays.asList("FP10871DE", "RMA", "KE8965", "HY10319WH", "SP36969");
        List<Pk> list = pkMapper.getEvenUpList(date, excludeSkuList);
        list = list.stream().filter(l -> !(l.getSku().equals("ES10327DE-OR") && l.getPlace().equals("EU113")))
                .collect(Collectors.toList());
        //库存
        List<TempKcjlDaily> kcList = tempKcjlDailyMapper.getListByDate(date);
        Map<String, TempKcjlDaily> kcMap = kcList.stream()
                .collect(Collectors.toMap(l -> l.getCpbh() + "_" + l.getPlace() + "_" + l.getBelongs(), i -> i));

        for (Pk pk : list) {
            String key = pk.getSku() + "_" + pk.getPlace() + "_" + pk.getBelongs();
            TempKcjlDaily kc = kcMap.get(key);
            if (Objects.isNull(kc)) {
                if (pk.getNum() > 0) {
                    addKcList.add(generatorEntityManager
                            .genTempKcjlDaily(pk.getSku(), pk.getBelongs(), pk.getPlace(), pk.getNum(), date));
                    continue;
                } else {
                    throw new RuntimeException("库存数据不存在:" + pk);
                }
            }
            kc.setSl(kc.getSl() + pk.getNum());
            updateKcList.add(kc);
        }
        System.out.println(1);
//        tempKcjlDailyMapper.insertBatchSomeColumn(addKcList);
//        updateKcList.forEach(tempKcjlDailyMapper::updateById);

    }

    @Override
    @DS("fa_eu")
    @DSTransactional
    public void evenUpPlace(String date) {
        List<TempPkpy> pkpyList = new LinkedList<>();
        List<String> placeList = Arrays.asList("EU01", "EU06", "EU115", "EU116", "EU97", "EU生资库");
        List<TempKcjlDaily> list = tempKcjlDailyMapper.getListByPlace(date, placeList);
        Date createTime = new Date();
        for (TempKcjlDaily daily : list) {
            pkpyList.add(BeanCopyUtils.copyPropertiesNew(daily, TempPkpy::new, (s, t) -> t.setCreateTime(createTime)));
        }
        temPkpyMapper.insertBatchSomeColumn(pkpyList);
        tempKcjlDailyMapper.deleteBatchIds(list.stream().map(TempKcjlDaily::getId).collect(Collectors.toList()));
    }

    @Override
    @DS("fa_eu")
    public void supplJpk() {

        List<JpkStockBO> allData = new ArrayList<>();

        List<String> sheetList = Arrays.asList("Dokumenty MAG", "MAG Wiersze");
        Map<String, Class> classMap = new HashMap<>();
        classMap.put("Dokumenty MAG", JpkInfoBO.class);
        classMap.put("MAG Wiersze", JpkRecordInfoBO.class);

        //盘盈数据
        List<JpkStockBO> pyList = pkMapper.get2024JpkPyList();

        //盘盈中需要扣减的数据
        List<JpkStockBO> deductionList = pkMapper.getDeductionList();
        if (!CollectionUtils.isEmpty(deductionList)) {
            for (JpkStockBO data : deductionList) {
                pyList.stream()
                        .filter(l -> l.getSku().equals(data.getSku()) && l.getBelongs().equals(data.getBelongs()))
                        .forEach(py -> {
                            if (data.getNum() == 0) {
                                return;
                            }
                            Integer incurNum = data.getNum();
                            int renamingNum = py.getNum() - incurNum;
                            if (renamingNum >= 0) {
                                data.setNum(0);
                                py.setNum(renamingNum);
                            } else {
                                data.setNum(Math.abs(renamingNum));
                                py.setNum(0);
                            }
                        });
            }
        }
        pyList = pyList.stream().filter(l -> !(l.getSku().equals("ES10327DE-OR") && l.getPlace().equals("EU113")) &&
                        l.getNum() != 0)
                .collect(Collectors.toList());
        allData.addAll(pyList);
        //盘亏数据
        List<JpkStockBO> pkList = pkMapper.get2024JpkPkList();
        allData.addAll(pkList);
        Map<String, List<JpkStockBO>> belongsMap = allData.stream().collect(Collectors.groupingBy(JpkStockBO::getBelongs));
        belongsMap.forEach((belongs, belongsGroupList) -> {
            List<JpkInfoBO> allInfoList = new LinkedList<>();
            List<JpkRecordInfoBO> allRecordList = new ArrayList<>();
            System.out.println(belongs);
            String fileName = "2024-12-" + belongs.split("-")[1].toLowerCase() + ".xlsx";
            String jpkPath = FileUtil.getExcelPath() + JPK_FOLDER_NAME;
            List<JpkInfoBO> jpkInfoList = EasyExcel.read(jpkPath + fileName).head(JpkInfoBO.class)
                    .sheet("Dokumenty MAG").doReadSync();
            String no = jpkInfoList.stream().map(l -> l.getNumber().substring(1, 10)).max(Comparator.naturalOrder()).get();
            AtomicInteger startNumber = new AtomicInteger(Integer.parseInt(no));
            Map<String, List<JpkStockBO>> typeMap = belongsGroupList.stream()
                    .collect(Collectors.groupingBy(JpkStockBO::getType));
            typeMap.forEach((type, typeGroupList) -> {
                Map<String, List<JpkStockBO>> placeMap = typeGroupList.stream()
                        .collect(Collectors.groupingBy(JpkStockBO::getPlace));
                placeMap.forEach((place, placeGroupList) -> {
                    startNumber.addAndGet(1);
                    StringBuffer sb = new StringBuffer();
                    List<JpkRecordInfoBO> recordList = BeanCopyUtils.copyListProperties(placeGroupList,
                            JpkRecordInfoBO::new, (s, t) -> {
                                if (StringUtils.isBlank(sb.toString())) {
                                    sb.append(type).append(startNumber.get()).append(s.getNo());
                                }
                                t.setNumber(sb.toString());
                                t.setNum(String.valueOf(s.getNum()));
                                t.setJm("szt");
                                t.setPrice(String.valueOf(s.getPrice()));
                                t.setTotalPrice(String.valueOf(s.getTotalPrice()));
                            });
                    allRecordList.addAll(recordList);
                    double sumPrice = placeGroupList.stream().mapToDouble(JpkStockBO::getTotalPrice).sum();
                    allInfoList.add(JpkInfoBO.builder().type(sb.substring(0, 2)).number(sb.substring(2))
                            .date("2024-12-31").operationDate("2024-12-31").invoiceDate("2024-12-31")
                            .place(place).totalPrice(String.valueOf(sumPrice)).build());
                });
            });
            //写入
            String newFileName = belongs.split("-")[1].toLowerCase() + ".xlsx";
            try (ExcelWriter excelWriter = EasyExcel.write(jpkPath + newFileName).build()) {
                for (int i = 0; i < sheetList.size(); i++) {
                    // 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样。
                    WriteSheet writeSheet = EasyExcel.writerSheet(i, sheetList.get(i)).head(classMap.get(sheetList.get(i))).build();
                    // 执行
                    switch (sheetList.get(i)) {
                        case "Dokumenty MAG":
                            excelWriter.write(allInfoList, writeSheet);
                            break;
                        case "MAG Wiersze":
                            excelWriter.write(allRecordList, writeSheet);
                            break;
                        default:
                            break;
                    }
                }
            }
        });
    }

    @Override
    @DS("fa_eu")
    @DSTransactional
    public void readProfitAndSupplPkPrice() {
        List<Pk> allPkList = new ArrayList<>();
        List<Pk> pkList = pkMapper.getProfitNoPlaceListByHistory();
        List<Pk> noPlace = pkList.stream().filter(l -> StringUtils.isBlank(l.getPlace())).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(noPlace)) {
            List<String> skuList = noPlace.stream().map(Pk::getSku).collect(Collectors.toList());
            List<Pk> otherPkList = pkMapper.getProfitNoPlaceListByKc(skuList);
            if (otherPkList.stream().anyMatch(l -> StringUtils.isBlank(l.getPlace()))) {
                List<String> deepSkuList = otherPkList.stream().filter(l -> StringUtils.isBlank(l.getPlace()))
                        .map(Pk::getSku).collect(Collectors.toList());
                //货权问题，深挖同国家
                List<TempKcjlDaily> deepList = pkMapper.getDeepSkuPkListBySku(deepSkuList);
                Map<String, TempKcjlDaily> deepSkuMap = deepList.stream()
                        .collect(Collectors.toMap(l -> l.getCpbh() + l.getBelongs().split("-")[1], i -> i, (k1, k2) -> k1));
                otherPkList.stream().filter(l -> StringUtils.isBlank(l.getPlace())).forEach(other -> {
                    String key = other.getSku() + other.getBelongs().split("-")[1].toUpperCase();
                    TempKcjlDaily daily = deepSkuMap.get(key);
                    if (Objects.nonNull(daily)) {
                        other.setPlace(daily.getPlace());
                    } else {
                        TempKcjlDaily finalKc = deepList.stream().filter(l -> l.getCpbh().equals(other.getSku()))
                                .findFirst().orElseThrow(RuntimeException::new);
                        other.setPlace(finalKc.getPlace());
                    }
                });
            }
            allPkList.addAll(pkList.stream().filter(l -> StringUtils.isNotBlank(l.getPlace())).collect(Collectors.toList()));
            allPkList.addAll(otherPkList);
        } else {
            allPkList.addAll(pkList);
        }
        if (allPkList.stream().anyMatch(l -> StringUtils.isBlank(l.getPlace()))) {
            List<String> noPlaceSkuList = allPkList.stream().filter(l -> StringUtils.isBlank(l.getPlace()))
                    .map(Pk::getSku).collect(Collectors.toList());
            throw new RuntimeException("数据还存在无仓库标记！！！未标记sku：" + noPlaceSkuList);
        }
        Map<String, List<Pk>> belongsMap = allPkList.stream().collect(Collectors.groupingBy(Pk::getBelongs));
        belongsMap.forEach((belongs, list) -> {
            String jpkPath = FileUtil.getExcelPath() + JPK_FOLDER_NAME + belongs + "_202412.csv";
            List<ProfitCheckBO> profitList = EasyExcel.read(jpkPath).head(ProfitCheckBO.class).sheet().doReadSync();
            profitList = profitList.stream().filter(l -> Objects.nonNull(l.getLost()) && l.getLost() != 0)
                    .collect(Collectors.toList());
            if (CollectionUtils.isEmpty(profitList)) {
                return;
            }
            for (Pk pk : list) {
                if (Objects.nonNull(pk.getPrice())) {
                    continue;
                }
                List<ProfitCheckBO> filterList = profitList.stream().filter(l -> l.getSku().equals(pk.getSku()))
                        .collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(filterList)) {
                    // num为负数
                    Integer num = pk.getNum();
                    // 循环次数
                    int times = 0;
                    // 总值
                    double eurTotal = 0D;
                    for (ProfitCheckBO bo : filterList) {
                        int renamingNum = bo.getLost() + num;
                        if (renamingNum >= 0) {
                            if (times == 0) {
                                double resPrice = Objects.isNull(bo.getInPriceEur()) ? bo.getInPriceUsd() : bo.getInPriceEur();
                                pk.setPrice(CurrencyConvertUtil.convertFenFromYuanStandard(resPrice));
                            } else {
                                double resPrice = DoubleUtil.round((eurTotal + bo.getInPriceEur()) / times, 2);
                                pk.setPrice(CurrencyConvertUtil.convertFenFromYuanStandard(resPrice));
                            }
                            System.out.println(bo.getSku() + ",pln结果：" + pk.getPrice());
                            break;
                        } else {
                            times += 1;
                            eurTotal += bo.getInPriceEur();
                            num = renamingNum;
                            System.out.println(bo.getSku() + ",次数：" + times + ",单价pln：" + eurTotal);
                        }
                    }
                } else {
                    throw new RuntimeException("余量不足，数据存在从错误");
                }
            }
        });
        allPkList.forEach(pkMapper::updateById);
    }

}
